﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.Forms;
using InfonavaEye.handler;
using InfonavaEye.model;
using InfonavaEye.util;
using Newtonsoft.Json;
using Sylan.Common.Util;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sylan.Common.Util;
using System.Collections.Generic;
using InfonavaEye.enums;
using System.Linq;
using InfonavaEye.Handler;
using System.Timers;
using System.ComponentModel;
using static InfonavaEye.handler.AutoCaptrueHandler;
using InfonavaEye.components;
using System.Diagnostics;

namespace InfonavaEye
{
    public partial class AutoCaptureFormForm : Form
    {
        /// <summary>
        /// 形状 1 线型，2 圆型
        /// </summary>
        private int shape = 1;

        /// <summary>
        /// 当前抓拍的图像路径
        /// </summary>
        private string currentImagePath = null;

        FormAutoSize formAutoSize;

        AutoCaptrueHandler autoCaptrueHandler = null;

        private CameraHandler cameraHandler = CameraHandler.Instance;

        private PLCHandler plcHandler = PLCHandler.Instance;

        FocusDistanceCurrentLimiter focusDistanceCurrentLimiter;

        public AutoCaptureFormForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
        }

        //不抢焦点,非活动窗口
        protected override bool ShowWithoutActivation => true;

        public OperationInfo OperationInfo { get; set; }


        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x112)
            {
                switch ((int)m.WParam)
                {
                    //禁止双击标题栏关闭窗体
                    case 0xF063:
                    case 0xF093:
                        m.WParam = IntPtr.Zero;
                        break;
                    //禁止拖拽标题栏还原窗体
                    case 0xF012:
                    case 0xF010:
                        m.WParam = IntPtr.Zero;
                        break;
                    //禁止双击标题栏
                    case 0xf122:
                        m.WParam = IntPtr.Zero;
                        break;
                        /* //禁止关闭按钮
                         case 0xF060:
                             m.WParam = IntPtr.Zero;
                             break;
                         //禁止最大化按钮
                         case 0xf020:
                             m.WParam = IntPtr.Zero;
                             break;
                         //禁止最小化按钮
                         case 0xf030:
                             m.WParam = IntPtr.Zero;
                             break;
                         //禁止还原按钮
                         case 0xf120:
                             m.WParam = IntPtr.Zero;
                             break;*/
                }
            }
            base.WndProc(ref m);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            FormDataBridge.ClearData();
            this.cameraHandler.IncreaseCurrentFileBatchNum();
            SoundHelper.PlayAudio("fixed.wav");

            //按照相机的长宽比来设置图片框大小
            capturePictureBox.Height = (int)(capturePictureBox.Width * 2048 / 3072);
            capturePictureBox.Refresh();
            drawingBox.Height = (int)(drawingBox.Width * 2048 / 3072);
            drawingBox.Refresh();

            //自动按照窗口调整组件的大小
            /* formAutoSize = new FormAutoSize();
             formAutoSize.afterSizeChangeDelegate += afterSizeChangeDelegate;
             formAutoSize.beforeSizeChangeDelegate += beforeSizeChangeDelegate;
             formAutoSize.controllInitializeSize(this);*/
            this.WindowState = FormWindowState.Maximized;
            this.Resize += new System.EventHandler(this.MainForm_Resize);
            this.btnAutoRunStart.Visible = false;
            this.btnAutoRunStop.Visible = false;

            FormDataBridge.receiveOCRResult += receiveOCRResult;
            FormDataBridge.appendResultDelegate += FormDataBridge_appendResultDelegate;

            //lblUsedTimes.Text = Config.OCR_USERD_TIME.ToString();
            focusDistanceCurrentLimiter = new FocusDistanceCurrentLimiter();

            #region 视频光标
            xCrossLine.Width = drawingBox.Width;
            xCrossLine.Height = 1;
            xCrossLine.Location = new Point(drawingBox.Location.X, drawingBox.Location.Y + drawingBox.Height / 2);

            yCrossLine.Width = 1;
            yCrossLine.Height = drawingBox.Height;
            yCrossLine.Location = new Point(drawingBox.Location.X + drawingBox.Width / 2, drawingBox.Location.Y);
            xCrossLine.Visible = false;
            yCrossLine.Visible = false;
            #endregion

            #region OCR识别结果
            this.loadingPictureBox.Image = Properties.Resources.loading;
            this.loadingPictureBox.Visible = false;
            this.lblCode.Text = "";
            this.lblCode.Text = "暂无结果";
            this.lblCode.Visible = false;
            this.lblLoading.Visible = false;
            this.lblResult1.Visible = false;
            #endregion

            this.startDevice();
        }
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.stopDevice();
            /* formAutoSize.afterSizeChangeDelegate -= afterSizeChangeDelegate;
            formAutoSize.beforeSizeChangeDelegate -= beforeSizeChangeDelegate;*/
            FormDataBridge.receiveOCRResult -= receiveOCRResult;
            FormDataBridge.appendResultDelegate -= FormDataBridge_appendResultDelegate;
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (cameraHandler.isCameraOpening)
            {
                e.Cancel = true; //取消关闭操作
                MessageBox.Show("相机正在连接中，无法中断，请稍后再尝试关闭", "提示", MessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 开启各种设备
        /// </summary>
        private void startDevice(bool openCamera = true, bool openPlC = true)
        {
            ThreadHelper.ExcuteThreadTask(() =>
            {
                if (autoCaptrueHandler != null) {
                    autoCaptrueHandler.captureComplelteDelegate -= AutoCaptrueHandler_captureComplelteDelegate;
                    autoCaptrueHandler.nailAutoMovingDelegate -= AutoCapturehandler_nailMoving;
                }

                if (openPlC)
                {
                    initCaptureTimer();
                    plcHandler.PLCInitCompleteDelegate += CameraHandler_PLCInitCompleteDelegate;
                    plcHandler.z2ZeroDelegate += CameraHandler_z2ZeroDelegate;
                    plcHandler.moveToOriginCompleteDelegate += CameraHandler_moveToOriginCompleteDelegate;
                    focusDistanceCurrentLimiter = new FocusDistanceCurrentLimiter();
                    plcHandler.StartPLC();
                }

                if (openCamera)
                {
                    cameraHandler.captureImageDelegate += CaptureImage;
                    cameraHandler.initCompleteDelegate += CameraHandler_initCompleteDelegate;
                    cameraHandler.play(this.drawingBox);
                }

                autoCaptrueHandler = new AutoCaptrueHandler(this, plcHandler, cameraHandler);
                autoCaptrueHandler.nailAutoMovingDelegate += AutoCapturehandler_nailMoving;
                autoCaptrueHandler.captureComplelteDelegate += AutoCaptrueHandler_captureComplelteDelegate;
            }, 50);
        }

        bool cbSampleChecked = false;
        private void CameraHandler_initCompleteDelegate()
        {
            if (!cbSampleChecked) {
                cbSample.Checked = true;
                cbSampleChecked = true;
            }
        }

        private void stopDevice(bool closeCamera = true, bool closePlC = true)
        {
            if (closeCamera)
            {
                cameraHandler.captureImageDelegate -= CaptureImage;
                cameraHandler.initCompleteDelegate -= CameraHandler_initCompleteDelegate;
                if (autoCaptrueHandler != null) {
                    autoCaptrueHandler.captureComplelteDelegate -= AutoCaptrueHandler_captureComplelteDelegate;
                    autoCaptrueHandler.nailAutoMovingDelegate -= AutoCapturehandler_nailMoving;
                }
            }

            if (closePlC)
            {
                if (captureTimer != null)
                {
                    captureTimerStoped = true;
                    captureTimer.Stop();
                }
                plcHandler.PLCInitCompleteDelegate -= CameraHandler_PLCInitCompleteDelegate;
                plcHandler.z2ZeroDelegate -= CameraHandler_z2ZeroDelegate;
                plcHandler.moveToOriginCompleteDelegate -= CameraHandler_moveToOriginCompleteDelegate;
            }
        }

        private bool captureTimerStoped = false;

        /// <summary>
        /// 读取抓拍按钮状态-定时器
        /// </summary>
        private System.Timers.Timer captureTimer;

        private void initCaptureTimer()
        {
            captureTimerStoped = false;
            captureTimer = new System.Timers.Timer();
            captureTimer.Interval = 80;
            //captureTimer.Enabled = true;
            captureTimer.AutoReset = false;
            captureTimer.Elapsed += new ElapsedEventHandler(Capture_Elapsed);
        }

        /// <summary>
        /// 抓拍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_Elapsed(object sender, EventArgs e)
        {
            try
            {
                captureTimer.Stop();
                if (plcHandler.checkCapturePressed())
                {
                    if (CameraHandler.captureing)
                    {
                        //MessageBox.Show("正在抓拍，请不要重复按抓拍按钮");
                        Console.WriteLine("正在抓拍，请不要重复按抓拍按钮");
                        return;
                    }

                    CameraHandler.captureing = true;
                    //TODO 调用相机的抓拍
                    cameraHandler.StartCapture();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("抓拍，发生异常：" + ex.StackTrace);
                MessageBox.Show("抓拍发生异常，请找管理员");
            }
            finally
            {
                if (!captureTimerStoped)
                {
                    captureTimer.Start();
                }
                //captureing = false;
            }
        }

        private void CameraHandler_PLCInitCompleteDelegate()
        {
            this.btnAutoRunStart.Visible = true;
            this.btnAutoRunStop.Visible = true;

            captureTimer.Start();

            if (!this.plcHandler.checkOrigin())
            {
                if (MessageBox.Show("开机需要回到机械原点，是否现在开始移动", "提示", MessageBoxButtons.OK) == DialogResult.OK)
                {
                    this.backToOrigin();
                }
            }
            //防止在其他地方初始化后 频繁调用这里
            plcHandler.PLCInitCompleteDelegate -= CameraHandler_PLCInitCompleteDelegate;
        }

        private void CameraHandler_moveToOriginCompleteDelegate()
        {
            toggleAutoRunStartStatus(true);
        }

        /// <summary>
        /// 切换开始按钮的状态
        /// </summary>
        /// <param name="enabled"></param>
        private void toggleAutoRunStartStatus(bool enabled) {
            if (enabled)
            {
                this.btnAutoRunStart.Enabled = true;
                this.btnAutoRunStart.Image = global::InfonavaEye.Properties.Resources.start;
            }
            else {
                this.btnAutoRunStart.Enabled = false;
                this.btnAutoRunStart.Image = global::InfonavaEye.Properties.Resources.start_disabled;
            }
        }

        private void AutoCaptrueHandler_captureComplelteDelegate()
        {
            this.autoMovinging = false;
            this.autoMovingStoped = true;
            toggleAutoRunStartStatus(true);
            this.lblBoxModel.Enabled = true;
            this.captureTimer.Start();
        }

        private void FormDataBridge_appendResultDelegate(OCRResult result)
        {
            if (drawingBox.IsHandleCreated && autoMovinging)
            {
                this.Invoke(new Action(() =>
                {
                    this.updateNailStatus(result);
                }));
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            drawingBox.Refresh();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
       
        private void label2_Click(object sender, EventArgs e)
        {
            this.shape = 1;
            this.lblResult1.Visible = true;
            this.lblCode.Visible = true;
            this.lblCode.Text = "暂无结果";
            this.label2.ForeColor = Color.FromArgb(255, 0, 77, 203);
        }

        private void label3_Click(object sender, EventArgs e)
        {
            this.shape = 2;
            this.loadingPictureBox.Visible = false;
            this.lblCode.Text = "";
            this.lblCode.Visible = false;
            this.lblLoading.Visible = false;
            this.lblResult1.Visible = false;

            this.label2.ForeColor = Color.FromArgb(255, 102, 102, 102);
        }

        private void label9_Click(object sender, EventArgs e)
        {
            this.shape = 1;
            this.lblResult1.Visible = true;
            this.lblCode.Visible = true;
            this.lblCode.Text = "暂无结果";
            this.label2.ForeColor = Color.FromArgb(255, 102, 102, 102);
        }

        private void paneLeft_Paint(object sender, PaintEventArgs e)
        {
            label2_Click(null, null);
        }

        private void linkResultList_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
        }

        private void CameraHandler_z2ZeroDelegate()
        {
            /*Thread.Sleep(500);
            this.focusDistanceTrackBar.Value = Config.CAMERA_FOCUS_DISTANCE;
            this.changeFocusDistance();*/
        }

        private void beforeSizeChangeDelegate()
        {
            Graphics g = drawingBox.CreateGraphics();
            g.Clear(Color.White);
            g.Dispose();
            drawingBox.Refresh();
        }

        float formWidthScale = 1;
        float formHeightScale = 1;
        private void afterSizeChangeDelegate(float wScale, float hScale)
        {
            formWidthScale = wScale;
            formHeightScale = hScale;
            
            //按照相机的长宽比来设置图片框大小
            drawingBox.Height = (int)(drawingBox.Width / 3072f * 2048f);

            //this.plcHandler.Close();
            //this.plcHandler.Start();
        }

        private void receiveOCRResult(OCRResult result)
        {
            this.Invoke(new Action(() =>
            {
                this.lblLoading.Visible = false;
                this.loadingPictureBox.Visible = false;
                this.lblCode.Visible = true;
                this.lblResult1.Visible = true;
                if (result.nail != null && result.nail.point != null)
                {
                    var rowTitle = (result.nail.area.columnTitle != null && result.nail.area.columnTitle.Length > 0) ? result.nail.area.columnTitle[result.nail.point.X] : "";
                    var locationStr = String.Format("{0} 》{1}:(x {2} y {3})", result.nail.area.name, rowTitle, result.nail.point.X + 1, result.nail.point.Y + 1);
                    this.lblNailInfo.Text = locationStr;
                }
                this.updateNailStatus(result);
                if (result.filePath.Equals(currentImagePath))
                {
                    this.lblCode.Text = result.code;
                }
                else
                {
                    this.lblCode.Text = "";
                }
                
            }));
        }

        private void btnCapture_Click(object sender, EventArgs e)
        {
            if (autoMovinging) return;
            //删除旧数据
            //FormDataBridge.removeOCRResult(currentImagePath);

            if (capturePictureBox.Image != null)
            {
                Graphics g = Graphics.FromImage(capturePictureBox.Image);
                g.Clear(Color.White);
                g.Dispose();
                capturePictureBox.Refresh();
                this.lblCode.Text = "";
            }

            //测试
            /* var basePath = "D:\\project\\code\\infynova-eye-desk\\InfonavaEye\\bin\\x64\\Debug\\Image\\2022-09-09\\1";
             var filePath = basePath + "\\160921_7.jpg";
             var newPath = basePath + "\\" + DateTime.Now.Ticks + ".jpg";
             File.Copy(filePath, newPath, true);
             this.CaptureImage(newPath);*/
            this.cameraHandler.StartCapture();
        }
        
        /// <summary>
        /// 自动移动钉子到目标坐标后更新预览图中的钉子图像
        /// </summary>
        /// <param name="nail"></param>
        private void AutoCapturehandler_nailMoving(Nail nail) {
            updateNailStatus(new OCRResult()
            {
                nail = nail,
            });
        }

        private void CaptureImage(string imagePath)
        {
            this.Invoke(new Action(() =>
            {
                currentImagePath = imagePath;
                this.capturePictureBox.Load(imagePath);
                if (this.shape == 1)
                {
                    this.lblCode.Text = "";
                    this.lblCode.Visible = false;
                    this.lblLoading.Visible = true;
                    this.loadingPictureBox.Visible = true;
                }

                FormDataBridge.appendOCRTask(imagePath, shape, cbSample.Checked);
                if (autoMovinging && !autoMovingStoped) {
                    autoCaptrueHandler.nailCapture();
                }
            }));
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            CameraSettingForm form = new CameraSettingForm();
            form.settingCloseDelegate += () =>
            {
                this.cameraHandler.play(this.drawingBox);
            };
            form.ShowDialog();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            //formAutoSize.controlAutoSize(this);
        }

        private void cbSample_CheckedChanged(object sender, EventArgs e)
        {
            if (cbSample.Checked)
            {
                this.cameraHandler.SetSample(cbSample.Checked);
            }
        }

        private void videoPictureBox_Paint(object sender, PaintEventArgs e)
        {
            PictureBox p = (PictureBox)sender;
            Pen pp = new Pen(Color.FromArgb(255, 0, 77, 203));
            e.Graphics.DrawRectangle(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - 1, e.ClipRectangle.Y + e.ClipRectangle.Height - 1);
        }

        private void linkDir_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string filePath = CameraHandler.CurrentBatchDir;
            if (String.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("未找到任何文件夹，请先拍照");
                return;
            }
            util.FileHelper.openDir(filePath);
        }

        #region 自动控制
        AutoStartParams autoStartParams = null;
        private bool autoMovinging = false;
        private bool autoMovingStoped = false;
        /// <summary>
        /// 校准原点的位置（x,y）
        /// </summary>
        private XYZ[] fixZeroLocation;

        /// <summary>
        /// 开启
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoRun_Click(object sender, EventArgs e)
        {
            doAutoRun();
        }

        private void doAutoRun() {
            if (autoMovinging) return;

            toggleAutoRunStartStatus(false);
            this.lblBoxModel.Enabled = false;
            this.cameraHandler.pause();//暂停视频

            SelectBoxTemplateStep1Form form = new SelectBoxTemplateStep1Form(this.lblBoxModel.Text, this.templateNailList);
            var dialogResult = form.ShowDialog();
            this.cameraHandler.play(this.drawingBox);//开始视频

            if (dialogResult == DialogResult.OK)
            {
                this.boxModel = form.boxModel;
                this.checkModel();
                this.lblBoxModel.Text = form.selectBoxModelName;
                this.templateNailList = form.templateNailList;
                this.lblNailCount.Text = String.Format("{0}个", form.templateNailList.Where(p => p.status == NailStatus.Selected).Count());
                this.fixZeroLocation = form.fixZeroLocation;
                this.drawAreas();
                //清空数据
                FormDataBridge.ClearData();
                this.cameraHandler.IncreaseCurrentFileBatchNum();

                autoMovinging = true;
                autoMovingStoped = false;
                Task.Factory.StartNew(async () =>
                {
                    captureTimer.Stop();
                    await Task.Delay(300);
                    autoStartParams = new AutoStartParams()
                    {
                        Stopwatch = new Stopwatch(),
                        BoxModel = this.boxModel,
                        BoxModelName = this.lblBoxModel.Text,
                        NailList = this.nailList,
                        TemplateNailList = this.templateNailList,
                        FixZeroLocations = this.fixZeroLocation,
                    };
                    this.drawAreas();
                    autoCaptrueHandler.start(autoStartParams);
                });
            }
            else
            {
                toggleAutoRunStartStatus(true);
                this.lblBoxModel.Enabled = true;
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoRunStop_Click(object sender, EventArgs e)
        {
            this.ActiveControl = null;
            autoMovinging = false;
            autoMovingStoped = true;
            FormDataBridge.clearAutoCaptureNailQueue();
            autoCaptrueHandler.stop();
            toggleAutoRunStartStatus(true);
            this.lblBoxModel.Enabled = true;
            captureTimer.Start();
            AutoCloseMessageBox.Show("停止命令发送成功");
        }

        /// <summary>
        /// 准备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrepare_Click(object sender, EventArgs e)
        {

        }

        private void btnPrepare_Paint(object sender, PaintEventArgs e)
        {
            Button p = (Button)sender;
            float penWidth = 2.0f;
            Pen pp = new Pen(Color.FromArgb(255, 0, 77, 203), penWidth);

            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.DrawEllipse(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - penWidth, e.ClipRectangle.Y + e.ClipRectangle.Height - penWidth);
        }
        #endregion 

        private void videoPictureBox_Click(object sender, EventArgs e)
        {

        }

        private void btnVideoRefresh_Click(object sender, EventArgs e)
        {
            drawingBox.Refresh();
        }

        private void chbCross_CheckedChanged(object sender, EventArgs e)
        {
            if (chbCross.Checked)
            {
                xCrossLine.Visible = true;
                yCrossLine.Visible = true;
            }
            else
            {
                xCrossLine.Visible = false;
                yCrossLine.Visible = false;
            }
        }

        private void pictureBox_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            GraphicsHelper.SetGDIHigh(g);
            Color bgColor = Color.FromArgb(255, 247, 247, 247);
            GraphicsHelper.FillRoundRectangle(e.ClipRectangle, g, 5, bgColor);
        }

        /// <summary>
        /// 模板的钉子 (主要是记录了钉子的选中状态，方便自动化的时候处理)
        /// </summary>
        public List<Nail> templateNailList = null;

        private void lblBoxModel_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
        {
                doAutoRun();
        }

        private void checkModel()
        {
            if (this.boxModel == null || String.IsNullOrEmpty(this.boxModel.boxName))
            {
                AutoCloseMessageBox.Show("检查到钉盒模板数据是空的，请重新建模");
                return;
            }
            if (this.boxModel.boxAreas == null || this.boxModel.boxAreas.Count == 0)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有配置区域，请重新建模");
                return;
            }

            var boxArea = this.boxModel.boxAreas[0];
            var rowCount = boxArea.rowCount;
            var columnCount = boxArea.columnCount;
            var startPoint = boxArea.startPoint;
            var holdPitch = boxArea.holdPitch;
            if (rowCount == 0)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有设置第一个区域的行数，请重新建模");
                return;
            }
            if (columnCount == 0)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有设置第一个区域的列数，请重新建模");
                return;
            }
            if (startPoint == null)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有设置第一个区域的起点，请重新建模");
                return;
            }
            if (holdPitch == null)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有设置第一个区域的孔距数据，请重新建模");
                return;
            }
            if (this.boxModel.boxAngle == -9999)
            {
                AutoCloseMessageBox.Show("检查到钉盒模板没有设置第一个区域的钉盒倾斜角度，请重新建模");
                return;
            }
        }

        private void linkOperating_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CreateOperationForm form = new CreateOperationForm(this.OperationInfo);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.newEntity != null)
                {
                    AutoCaptureFormForm mainform = new AutoCaptureFormForm();
                    mainform.OperationInfo = form.newEntity;
                    mainform.Show();
                }
            }
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void lblFocusDistance_Click(object sender, EventArgs e)
        {

        }

        private void btnRefreshPic_Click(object sender, EventArgs e)
        {
            ThreadHelper.ExcuteThreadTask(() =>
            {
                this.cameraHandler.play(this.drawingBox);
            });
        }

        private void backToOrigin()
        {
            toggleAutoRunStartStatus(false);
            ThreadHelper.ExcuteThreadTask(() =>
            {
                plcHandler.moveToOrigin();
                toggleAutoRunStartStatus(true);
            });
        }

        private void btnViewList_Click(object sender, EventArgs e)
        {
            //this.cameraHandler.pause();//暂停视频
            CaptureResultForm form = new CaptureResultForm();
            form.boxModel = this.boxModel;
            form.ListCloseDelegate += () =>
            {
                this.cameraHandler.play(this.drawingBox);//重新显示视频
            };
            form.clearListDelegate += () =>
            {
                //ListForm清除了数据，就需要增加新文件夹
                this.cameraHandler.IncreaseCurrentFileBatchNum();
            };
            form.Show();
        }
    }
}
